package com.ebei.platform.common.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.EntityBuilder;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.zip.GZIPInputStream;

public class HttpRequestUtils {

    private static Logger logger = LoggerFactory.getLogger(HttpRequestUtils.class);

    public static HttpResponse getHttpResponse(String url, Map<String, String> params) throws Exception {
        int CONNECTION_TIMEOUT = 2 * 60 * 1000;
        RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(CONNECTION_TIMEOUT)
                .setConnectTimeout(CONNECTION_TIMEOUT).setSocketTimeout(CONNECTION_TIMEOUT).build();
        
        CloseableHttpClient httpclient = HttpClients.createDefault();
        
        HttpGet httpGet = new HttpGet(new URI(url));
        httpGet.setConfig(requestConfig);
        for (Map.Entry<String, String> entry : params.entrySet()) {
            httpGet.setHeader(entry.getKey(), entry.getValue());
        }

        CloseableHttpResponse response = httpclient.execute(httpGet);
        return response;
    }

    public static HttpURLConnection getUrlConnection(String url, int bufferSize) throws Exception {
        URL target = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) target.openConnection();
        conn.setConnectTimeout(30000);
        conn.setReadTimeout(30000);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("connection", "Keep-Alive");
        conn.setChunkedStreamingMode(bufferSize);
        conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
        conn.setRequestProperty("Charsert", "UTF-8");
        conn.setRequestProperty("contentType", "UTF-8");
        conn.setRequestProperty("timenow", String.valueOf(System.currentTimeMillis()));
        return conn;
    }

    /**
     * get 请求
     */
    public static String sendGet(String url, Map<String, String> params) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = null;
            StringBuffer sBuffer = new StringBuffer();
            for ( Map.Entry<String, String> entry : params.entrySet()) {
                if (!RestfulConstants.TOKEN_VALID_KEY.equals(entry.getKey())) {
                    sBuffer.append(entry.getKey() + "=" + entry.getValue() + "&");
                }
            }
            if (sBuffer.length() > 0) {
                sBuffer.deleteCharAt(sBuffer.length()-1);
            }
            
            if (url.indexOf("?") > 0 ) {
                urlNameString = url + "&" + sBuffer.toString();
            } else {
                urlNameString = url + "?" + sBuffer.toString();
            }
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            if (params.containsKey(RestfulConstants.TOKEN_VALID_KEY)) {
                connection.setRequestProperty(RestfulConstants.TOKEN_VALID_KEY, params.get(RestfulConstants.TOKEN_VALID_KEY));
            }
            // 建立实际的连接
            connection.connect();
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            logger.info("发送GET请求出现异常！" + e);
            System.out.println("发送GET请求出现异常！" + e);
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 
     * Discription : post发送请求
     * 
     * @param url
     * @param params 参数 各入如：map.put(key,value);
     * @return String
     * @date 2013-12-27 下午4:21:49
     */
    public static String sendPost(String url, Map<String, String> params) {
        URL u = null;
        HttpURLConnection con = null;
        // 构建请求参数
        StringBuffer sb = new StringBuffer();
        if (params != null) {
            for (Entry<String, String> e : params.entrySet()) {
                if (RestfulConstants.TOKEN_VALID_KEY.equals(e.getKey())) {
                    continue;
                }
                sb.append(e.getKey());
                sb.append("=");
                sb.append(e.getValue());
                sb.append("&");
            }
            if (sb.length() > 0) {
                sb.deleteCharAt(sb.length()-1);
            }
        }
        // 尝试发送请求
        try {
            u = new URL(url);
            con = (HttpURLConnection) u.openConnection();
            con.setRequestMethod("POST");
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setUseCaches(false);
            if (params.containsKey(RestfulConstants.TOKEN_VALID_KEY)) {
                con.setRequestProperty(RestfulConstants.TOKEN_VALID_KEY, params.get(RestfulConstants.TOKEN_VALID_KEY));
            }
            con.setRequestProperty("accept", "*/*");
            con.setRequestProperty("connection", "Keep-Alive");
            con.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
            osw.write(sb.toString());
            osw.flush();
            osw.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (con != null) {
                con.disconnect();
            }
        }

        // 读取返回内容
        StringBuffer buffer = new StringBuffer();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
            String temp;
            while ((temp = br.readLine()) != null) {
                buffer.append(temp);
                buffer.append("\n");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return buffer.toString();
    }

    public static String sendPost(String url, String params) {
        URL u = null;
        HttpURLConnection con = null;
        // 构建请求参数
        StringBuffer sb = new StringBuffer();
        sb.append(params);

        // 尝试发送请求
        try {
            u = new URL(url);
            con = (HttpURLConnection) u.openConnection();
            con.setRequestMethod("POST");
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setUseCaches(false);
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
            osw.write(sb.toString());
            osw.flush();
            osw.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (con != null) {
                con.disconnect();
            }
        }

        // 读取返回内容
        StringBuffer buffer = new StringBuffer();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
            String temp;
            while ((temp = br.readLine()) != null) {
                buffer.append(temp);
                buffer.append("\n");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return buffer.toString();
    }

    public static String sendHttpPost(String url, Map<String, String> params) {
        // 创建默认的httpClient实例.
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建httppost
        HttpPost httppost = new HttpPost(url);
        // 创建参数队列
        List<BasicNameValuePair> formparams = new ArrayList<BasicNameValuePair>();
        BasicNameValuePair valuePair = null;
        if (params != null && params.size() > 0) {
            for (String key : params.keySet()) {
                valuePair = new BasicNameValuePair(key, params.get(key));
                formparams.add(valuePair);
            }
        }
        UrlEncodedFormEntity uefEntity;
        String result = "";
        try {
            uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
            httppost.setEntity(uefEntity);
            System.out.println("executing request " + httppost.getURI());
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                org.apache.http.HttpEntity entity =  response.getEntity();
                if (entity != null) {
                    result = EntityUtils.toString((org.apache.http.HttpEntity) entity, "UTF-8");
                }
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        } catch (IOException e2) {
            e2.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return result;
    }

    public static String sendHttpPost(String url, Map<String, String> params, String charSet) {
        // 创建默认的httpClient实例.
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建httppost
        HttpPost httppost = new HttpPost(url);
        // 创建参数队列
        List<BasicNameValuePair> formparams = new ArrayList<BasicNameValuePair>();
        BasicNameValuePair valuePair = null;
        if (params != null && params.size() > 0) {
            for (String key : params.keySet()) {
                valuePair = new BasicNameValuePair(key, params.get(key));
                formparams.add(valuePair);
            }
        }
        UrlEncodedFormEntity uefEntity;
        String result = "";
        try {
            uefEntity = new UrlEncodedFormEntity(formparams, charSet);
            httppost.setEntity(uefEntity);
            System.out.println("executing request " + httppost.getURI());
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                org.apache.http.HttpEntity entity =  response.getEntity();
                if (entity != null) {
                    result = EntityUtils.toString((org.apache.http.HttpEntity) entity, "UTF-8");
                }
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        } catch (IOException e2) {
            e2.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return result;
    }

    public static String analyzeGetGzip(String url, String param) throws Exception {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("Pragma", "no-cache");
            connection.setConnectTimeout(5000);
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            // Map<String, List<String>> map = connection.getHeaderFields();
            InputStream urlStream = new GZIPInputStream(connection.getInputStream());
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(urlStream));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }
    
    /**
     * 用于工程桌面获取redis缓存
     * @param url
     * @param params
     * @return
     */
    public static String sendRedisPost(String url, String params) {
        URL u = null;
        HttpURLConnection con = null;
        // 构建请求参数
        StringBuffer sb = new StringBuffer();
        sb.append(params);

        // 尝试发送请求
        try {
            u = new URL(url);
            con = (HttpURLConnection) u.openConnection();
            con.setRequestMethod("POST");
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setUseCaches(false);
            con.setRequestProperty("Content-Type", "application/json");
            OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
            osw.write(sb.toString());
            osw.flush();
            osw.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (con != null) {
                con.disconnect();
            }
        }

        // 读取返回内容
        StringBuffer buffer = new StringBuffer();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
            String temp;
            while ((temp = br.readLine()) != null) {
                buffer.append(temp);
                buffer.append("\n");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return buffer.toString();
    }

    public static JSONObject postRequestByHeaderAuthorization(String url, String parameter, String authorization) {
		HttpEntity httpEntity = EntityBuilder.create().setText(parameter).setContentEncoding("utf-8").setContentType(ContentType.APPLICATION_JSON).build();
		return postRequestByHeaderAuthorization(url, httpEntity, authorization);
	}
    
	public static JSONObject postRequestByHeaderAuthorization(String url, HttpEntity httpEntity, String authorization) {
		HttpPost httpPost = null;
		CloseableHttpClient client = null;
		CloseableHttpResponse response = null;
		JSONObject json = new JSONObject();
		try {
			httpPost = new HttpPost(url);
//			httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
			httpPost.addHeader("Authorization", authorization);

			httpPost.setEntity(httpEntity);
			client = HttpClients.createDefault();
			response = client.execute(httpPost);
			HttpEntity entity = response.getEntity();
			String result = EntityUtils.toString(entity, "UTF-8");
			json.put("statusCode", response.getStatusLine().getStatusCode());
			json.put("resultMsg", result);
		} catch (IOException e) {
			json.put("error", e);
		} finally {
			if (httpPost != null) {
				httpPost.releaseConnection();
			}
			if (client != null) {
				try {
					client.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return json;
	}
	
    public static void main(String[] args) {
        String testUrl = "127.0.0.1:8080/hermes/rest/speciality/saveSpeciality";
        Map<String, String> param = new HashMap<String, String>();
        param.put("UserName", "zhugl");
        param.put("Password", "123456");
        String result2 = HttpRequestUtils.sendGet(testUrl, param);
        String result3 = HttpRequestUtils.sendPost(testUrl, param);
        String result4 = HttpRequestUtils.sendHttpPost(testUrl, param);
        System.out.println(result2);
        System.out.println(result3);
        System.out.println(result4);
    }

}
